import { Form } from "antd";
import { useMemoizedFn, useMount } from "ahooks";
import * as rpcApis from "@/ui/utils/rpc";
import { message } from "antd";

export interface Props {
  onSaveDone?: () => void;
}

export const useViewModel = (props: Props) => {
  const form = Form.useForm()[0];

  const onSaveClick = useMemoizedFn(async () => {
    try {
      const data = await form.validateFields();
      await rpcApis.settings.setAll(data);
      message.success("保存成功");
      if (props.onSaveDone) {
        props.onSaveDone();
      }
    } catch (err) {
      console.error(err);
      message.success(`保存失败：${(err as Error)?.message ?? err}`);
    }
  });

  useMount(async () => {
    const data = await rpcApis.settings.getAll();
    form.setFieldsValue(data);
  });

  return { form, onSaveClick };
};
